package nl.ceasaro.jeslee.webapp.util;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 * User: cees
 * Date: Dec 23, 2007
 * Time: 10:32:46 PM
 * <p>
 * Cookie utility class for handling cookies
 * </p>
 */
public class CookieUtils
{
   private CookieUtils()
   {
   }

   /**
    * @param request      http servlet request
    * @param cookieName   the name of the cookie to look for
    * @param defaultValue returned in no cookie could be found.
    * @return the value of the cookie or the default value if no cookie could be found.
    */
   public static String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue)
   {
      Cookie cookie = getCookie(request, cookieName);
      return cookie == null ? defaultValue : cookie.getValue();
   }

   /**
    * @param request    http servlet request
    * @param cookieName the name of the cookie to look for
    * @return the found {@link Cookie} or <i>null</i> of none found.
    */
   public static Cookie getCookie(HttpServletRequest request, String cookieName)
   {
      Cookie[] cookies = request.getCookies();
      Cookie result = null;
      if (StringUtils.isNotEmpty(cookieName))
      {
         for (Cookie cookie : cookies)
         {
            if (cookieName.equals(cookie.getName()))
            {
               result = cookie;
            }
         }
      }
      return result;
   }
}
